import { Component, OnInit } from '@angular/core';
import { Book } from '../book';
import { BooksService } from '../service/books.service';
import { Router } from '@angular/router';
@Component({
  selector: 'app-master-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {

  books: Book[];
  selectedBook: Book;
  tip: string;
  constructor(
    private booksService: BooksService,
    private router: Router) { }

    getBooks(): void {
    this.booksService
        .getBooks()
        .then(books => this.books = books);
        }

  add(bid: string,bname: string,description: string,number: number): void {
    bid = bid.trim();
    bname = bname.trim();
    description = description.trim();
    if(!bid){
      this.tip = '书籍编号不能为空，请检查后重新输入！';
      console.log("书籍编号不能为空，请检查后重新输入！");
      //alert("书籍编号不能为空，请检查后重新输入！");
      return;
    }
    if (!bname){
      this.tip = '书籍名称不能为空，请检查后重新输入！';
      console.log("书籍名称不能为空，请检查后重新输入！");
      //alert("书籍名称不能为空，请检查后重新输入！");
      return;
    }
    if(number < 0 || !number){
      this.tip = '书籍数量不能小于零，不能为空，且为整型，请检查后重新输入！';
      console.log("书籍数量不能小于零，不能为空，且为整型，请检查后重新输入！");
      //alert("书籍数量不能小于零，不能为空，且为整型，请检查后重新输入！");
      return;
    }
    this.tip = '新书入库成功！';
    this.booksService.createBookByAll(bid,bname,description,number)
      .then(books => {
        this.books.push(books);
        this.selectedBook = null;
      });
  }

  ngOnInit(): void {
    this.getBooks();
  }

  onSelect(book: Book): void {
    this.selectedBook = book;
    this.gotoDetail();
  }

  gotoDetail(): void {
    this.router.navigate(['/books', this.selectedBook.id]);
  }

}
